package com.clayecloud.module_login.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.clayecloud.lib_base.action.ToastAction;
import com.clayecloud.lib_base.utils.KeyboradUtil;
import com.clayecloud.module_login.R;
import com.clayecloud.module_login.databinding.ActivityRegisterBinding;
import com.clayecloud.module_login.entity.RegisterUser;
import com.clayecloud.module_login.ui.dialog.BaseDialog;
import com.clayecloud.module_login.ui.dialog.MenuDialog;
import com.clayecloud.module_login.viewModels.RegisterActivityViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.OnTitleBarListener;

import java.util.ArrayList;
import java.util.List;

@Route(path = "/login/register/index")
public class RegisterActivity extends AppCompatActivity implements ToastAction {

    private ActivityRegisterBinding activityRegisterBinding;
    private RegisterActivityViewModel registerActivityViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register);
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());
        ViewModelProvider viewModelProvider = new ViewModelProvider(this, factory);
        registerActivityViewModel = viewModelProvider.get(RegisterActivityViewModel.class);
        registerActivityViewModel.leadData();
        activityRegisterBinding.setRegisterUser(registerActivityViewModel);
        init();
        initListener();
    }
    public void init(){
        //沉浸式状态栏
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    public void initListener(){
        //顶部导航栏监听
        activityRegisterBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View view) {
                finish();
                overridePendingTransition(R.anim.window_fake, R.anim.window_right_out);
            }

            @Override
            public void onTitleClick(View view) {
            }

            @Override
            public void onRightClick(View view) {
                List<String> data = new ArrayList<>();
                data.add("找回密码");
                data.add("人工申诉账号找回");
                // 底部选择框
                new MenuDialog.Builder(activityRegisterBinding.getRoot().getContext())
                        .setList(data)
                        .setListener(new MenuDialog.OnListener<String>() {
                            @Override
                            public void onSelected(BaseDialog dialog, int position, String string) {
                                toast("位置：" + position + "，文本：" + string);
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {
                                toast("取消了");
                            }
                        })
                        .show();
            }
        });

        //验证码按钮点击处理
        activityRegisterBinding.countdownView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toast("验证码已发送，请注意查收");
                activityRegisterBinding.countdownView.start();
            }
        });

        //监听控制按钮状态
        registerActivityViewModel.getRegisterUserMutableLiveData().getValue().addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                buttonStateChanger();
            }
        });

        activityRegisterBinding.registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 需要进行校验 然后传送  以后可以写
                registerActivityViewModel.register();
            }
        });

        registerActivityViewModel.getRegisterState().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    finish();
                    overridePendingTransition(R.anim.window_fake, R.anim.window_bottom_out);
                }
            }
        });

    }

    /**
     * 在删除此Activity时 进行操作防止内存泄漏
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        ImmersionBar.destroy(this, null);
    }

    /**
     * 重写每次点击事件，并进行判断是不是editText
     * @param motionEvent
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (KeyboradUtil.isShouldHideInput(v, motionEvent)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(motionEvent);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(motionEvent)) {
            return true;
        }
        return onTouchEvent(motionEvent);
    }

    /**
     * 判断是否更新按钮的状态
     */
    private void buttonStateChanger(){
        activityRegisterBinding.registerButton.setEnabled(false);
        RegisterUser registerUser = registerActivityViewModel.getRegisterUserMutableLiveData().getValue();
        if (registerUser.getStr_phone() == null || registerUser.getStr_verificationCode() == null || registerUser.getStr_loginPassword() == null || registerUser.getStr_re_loginPassword() == null
                || registerUser.getStr_email() == null || registerUser.getStr_username() == null){
            return;
        }
        if (!"".equals(registerUser.getStr_phone()) && !"".equals(registerUser.getStr_verificationCode()) && !"".equals(registerUser.getStr_loginPassword())
                && !"".equals(registerUser.getStr_re_loginPassword()) && !"".equals(registerUser.getStr_username()) && !"".equals(registerUser.getStr_email()) && registerUser.getBool_isRead()){
            activityRegisterBinding.registerButton.setEnabled(true);
        }
    }


}
